package ar.com.ironsoft.javaopenauth.oauth;

import java.util.Map;
import java.util.Set;

import ar.com.ironsoft.javaopenauth.dto.OAuthToken;
import ar.com.ironsoft.javaopenauth.url.URLService;
import ar.com.ironsoft.javaopenauth.utils.MapUtils;
import ar.com.ironsoft.javaopenauth.utils.ServletActionType;
import ar.com.ironsoft.javaopenauth.utils.ValidatorUtils;

public abstract class OAuthServiceV2 extends OAuthService{

	
	
	public OAuthServiceV2(String controllerUrlMapping,
			Set<ServletActionType> registeredActions) {
		super(controllerUrlMapping, registeredActions);
	}
	
	public OAuthServiceV2(String controllerUrlMapping,
			Set<ServletActionType> registeredActions,String clientKeysFilename) {
		super(controllerUrlMapping, registeredActions,clientKeysFilename);
	}	
	
	public String getLoginURL() {
		String url = getOauthProperties().getProperty(
				controllerUrlMapping+".url.request_token");
		url = url.replace("{0}", getApiKey()).replace("{1}",
				getCallbackURL());

		return url;
	}
	
	public OAuthToken getRefreshToken() {
		throw new UnsupportedOperationException(
				"OAuth V2 implementations not have a refresh token");
	}

	public void executeCallbackAction(String urlParameters) {
		Map<String,String> params = MapUtils.queryStringToMap(urlParameters);
		oauthToken.setVerificationCode(params.get("code"));
		getAccessToken();
	}
	
	public OAuthToken getAccessToken() {
		ValidatorUtils.validateNullOrEmpty(oauthToken.getVerificationCode());
		
		String url = getAccessTokenURL();
		url = url.replace("{0}", getApiKey());
		url = url.replace("{1}", getCallbackURL());
		url = url.replace("{2}", getConsumerSecret());
		url = url.replace("{3}", oauthToken.getVerificationCode());
		
		URLService urlService = new URLService();
		Map<String,String> response = urlService.fetchUrl(url);
		
		oauthToken.setAccessToken(response.get("access_token"));
		if (response.get("expires") != null)
		oauthToken.setAccessTokenExpireTime(Integer.parseInt(response
				.get("expires")));
		
		return oauthToken;
	}
}
